<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="w-100"
        v-model="queryForm.keyword"
        placeholder="关键字搜索"
      />
      <el-select
        class="w-100"
        v-model="queryForm.orderType"
        placeholder="订单类型"
      >
        <el-option label="全部" value="" />
        <el-option label="前台订单" value="formal" />
        <el-option label="定制商品订单" value="custom" />
      </el-select>

      <el-button type="primary" :icon="Search" @click="handleSearchWithFilter"
        >搜索</el-button
      >
      <el-button
        class="green-button"
        :icon="Plus"
        @click="refreshTableInfoWithFilter"
        >刷新</el-button
      >
      <!-- 批量删除按钮 -->
      <el-button
        type="danger"
        :icon="Delete"
        @click="batchDelete"
        :disabled="selectedRows.length === 0"
      >
        批量删除 ({{ selectedRows.length }})
      </el-button>
      <!-- 批量下载按钮 -->
      <el-button
        type="success"
        :icon="Download"
        @click="batchDownload"
        :disabled="selectedRows.length === 0"
        :loading="downloadLoading"
      >
        下载选中订单 ({{ selectedRows.length }})
      </el-button>
    </div>
    <!-- 批量操作提示 -->

    <el-tabs
      v-model="activeName"
      type="card"
      class="demo-tabs"
      @tab-click="handleClick"
    >
      <el-tab-pane label="全部" name=""></el-tab-pane>
      <el-tab-pane label="待确认" name="PENDING"></el-tab-pane>
      <el-tab-pane label="待发货" name="PENDING_SHIP"></el-tab-pane>
      <el-tab-pane label="已发货" name="SHIPPED"></el-tab-pane>
      <el-tab-pane label="待付款" name="PENDING_PAYMENT"></el-tab-pane>
      <el-tab-pane label="已完成" name="COMPLETED"></el-tab-pane>
      <el-tab-pane label="申请退货" name="RETURN_REQUESTED"></el-tab-pane>
      <el-tab-pane label="退货同意" name="RETURN_APPROVED"></el-tab-pane>
      <el-tab-pane label="退货拒绝" name="RETURN_REJECTED"></el-tab-pane>
      <el-tab-pane label="已退货" name="RETURNED"></el-tab-pane>
      <el-tab-pane label="已取消" name="CANCELLED"></el-tab-pane>
    </el-tabs>
    <div class="table-con">
      <div v-if="selectedRows.length > 0" class="batch-tip">
        已选择 {{ selectedRows.length }} 项
        <el-button type="primary" link @click="clearSelection"
          >清除选择</el-button
        >
      </div>
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
        @row-contextmenu="handleRowContextmenu"
        @selection-change="handleSelectionChange"
        border
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="40" />
        <el-table-column prop="id" label="订单编号" width="200" />
        <el-table-column label="下单时间" width="170">
          <template #default="scope">
            {{ dayjs(scope.row.orderTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column label="用户信息" width="220">
          <template #default="scope">
            <div>
              <div>姓名：{{ scope.row.customer?.nickName || "-" }}</div>
              <div>电话：{{ scope.row.customer?.phone || "-" }}</div>
              <div>单位：{{ scope.row.customer?.unit || "-" }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status || '')">
              {{ getStatusText(scope.row.status || "") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" width="120">
          <template #default="scope">
            {{ getDisplayAmount(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="订单类型" width="130">
          <template #default="scope">
            {{ scope.row.creator === "system" ? "定制商品订单" : "前台订单" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="onDetailsClick(scope.row)"
              >详情</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="onEditStatus(scope.row)"
              >修改订单状态</el-button
            >
            <el-button
              v-if="
                scope.row.status === 'COMPLETED' ||
                scope.row.status === 'RETURNED'
              "
              link
              type="success"
              size="small"
              @click="uploadInvoice(scope.row)"
              >上传发票</el-button
            >
            <el-popconfirm
              class="box-item"
              title="确认删除该项?"
              placement="left"
              @confirm="confirmEvent(scope.row)"
              @cancel="cancelEvent"
              :hide-icon="true"
            >
              <template #reference>
                <el-button link size="small" class="mt-3 mb-3">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Pagination
      v-model:page="pagination.page"
      v-model:size="pagination.pageSize"
      :total="total"
      @pagination="getTableDataWithFilter"
    />
    <div>
      <ContextMenu v-model:show="show" :options="optionsComponent">
        <ContextMenuItem label="操作1" @click="onMenuClick(1)" />
        <ContextMenuGroup label="操作2">
          <ContextMenuItem label="Item1" @click="onMenuClick(2)" />
          <ContextMenuItem label="Item2" @click="onMenuClick(3)" />
          <ContextMenuItem label="Item3" @click="onMenuClick(3)" />
          <ContextMenuGroup label="Child with v-for 8">
            <ContextMenuItem
              v-for="index of 6"
              :key="index"
              :label="'Item3-' + index"
              @click="onLoopMenuClick(index)"
            />
          </ContextMenuGroup>
        </ContextMenuGroup>
        <ContextMenuItem label="刷新" @click="onMenuClick(1)">
          <template #icon>
            <Refresh style="width: 1em; height: 1em; margin-right: 8px" />
          </template>
        </ContextMenuItem>
        <ContextMenuItem label="删除" @click="onMenuClick(1)">
          <template #icon>
            <Delete style="width: 1em; height: 1em; margin-right: 8px" />
          </template>
        </ContextMenuItem>
      </ContextMenu>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailsVisible"
      title="订单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="order-details">
        <!-- 基本信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单编号">{{
              currentOrder.id
            }}</el-descriptions-item>
            <el-descriptions-item label="订单价格"
              >¥{{ getDisplayAmount(currentOrder) }}</el-descriptions-item
            >
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(currentOrder.status || '')">
                {{ getStatusText(currentOrder.status || "") }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="下单时间">{{
              dayjs(currentOrder.orderTime).format("YYYY-MM-DD HH:mm:ss")
            }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 客户信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>客户信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="客户ID">{{
              currentOrder.customer?.id || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="客户昵称">{{
              currentOrder.customer?.nickName || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="客户电话">{{
              currentOrder.customer?.phone || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="客户单位">{{
              currentOrder.customer?.unit || "-"
            }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 收货地址 -->
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>收货地址</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="收货人姓名">{{
              currentOrder.address?.name || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="收货人电话">{{
              currentOrder.address?.phone || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="完整收货地址">
              <div class="address-detail">
                {{ getFullAddress(currentOrder.address) }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 退货信息 (仅在退货状态时显示) -->
        <el-card v-if="shouldShowReturnInfo(currentOrder.status)" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>退货信息</span>
            </div>
          </template>

          <el-descriptions :column="1" border>
            <el-descriptions-item
              v-if="currentOrder.returnReason"
              label="退货原因"
              >{{ currentOrder.returnReason }}</el-descriptions-item
            >
            <el-descriptions-item
              v-if="currentOrder.adminReturnRemark"
              label="管理员备注"
              >{{ currentOrder.adminReturnRemark }}</el-descriptions-item
            >
            <el-descriptions-item
              v-if="currentOrder.returnRequestTime"
              label="申请退货时间"
              >{{
                dayjs(currentOrder.returnRequestTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                )
              }}</el-descriptions-item
            >
            <el-descriptions-item
              v-if="currentOrder.returnProcessTime"
              label="处理时间"
              >{{
                dayjs(currentOrder.returnProcessTime).format(
                  "YYYY-MM-DD HH:mm:ss"
                )
              }}</el-descriptions-item
            >
            <!-- 退货商品列表 -->
            <el-descriptions-item
              v-if="getReturnItems(currentOrder).length > 0"
              label="退货商品"
            >
              <el-table
                :data="getReturnItems(currentOrder)"
                border
                size="small"
                style="width: 100%"
                :header-cell-style="{ background: '#f8f9fa', color: '#333' }"
              >
                <el-table-column label="商品名称" width="200">
                  <template #default="scope">
                    <div class="product-info">
                      <div class="product-name">
                        {{ scope.row.product?.pName || "未知商品" }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="商品品牌" width="100">
                  <template #default="scope">
                    <div class="product-info">
                      <div class="product-name">
                        {{ scope.row.product?.pBrand || "未知商品" }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="商品类型" width="100" align="center">
                  <template #default="scope">
                    {{ scope.row.product?.pType || "未分类" }}
                  </template>
                </el-table-column>

                <el-table-column label="商品价格" width="120" align="center">
                  <template #default="scope">
                    ￥{{ scope.row.product?.pPrice }}
                  </template>
                </el-table-column>

                <el-table-column label="退货数量" width="100" align="center">
                  <template #default="scope">
                    <span class="quantity-text">{{
                      scope.row.returnQuantity || scope.row.pNumber
                    }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 发票信息 (在已完成订单或已退货订单时显示) -->
        <el-card
          v-if="
            currentOrder.status === 'COMPLETED' ||
            currentOrder.status === 'RETURNED'
          "
          class="mb-4"
        >
          <template #header>
            <div class="card-header">
              <span>发票信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="发票抬头">{{
              currentOrder.invoiceInfo?.invoiceTitle || "未填写"
            }}</el-descriptions-item>
            <el-descriptions-item label="单位税号">{{
              currentOrder.invoiceInfo?.invoiceTaxNumber || "未填写"
            }}</el-descriptions-item>
            <el-descriptions-item label="注册地址">{{
              currentOrder.invoiceInfo?.invoiceAddress || "未填写"
            }}</el-descriptions-item>
            <el-descriptions-item label="注册电话">{{
              currentOrder.invoiceInfo?.invoicePhone || "未填写"
            }}</el-descriptions-item>
            <el-descriptions-item label="开户银行">{{
              currentOrder.invoiceInfo?.invoiceBank || "未填写"
            }}</el-descriptions-item>
            <el-descriptions-item label="银行账户">{{
              currentOrder.invoiceInfo?.invoiceBankAccount || "未填写"
            }}</el-descriptions-item>
            <el-descriptions-item label="发票备注" :span="2">{{
              currentOrder.invoiceInfo?.invoiceRemark || "无"
            }}</el-descriptions-item>
            <el-descriptions-item label="发票文件" :span="2">
              <div v-if="currentOrder.invoiceImageUrl">
                <div class="invoice-file-info">
                  <div class="file-name">
                    {{ getInvoiceFileName(currentOrder.invoiceImageUrl) }}
                  </div>
                  <div class="file-type">
                    {{ getInvoiceFileType(currentOrder.invoiceImageUrl) }}
                  </div>
                </div>
                <div class="mt-2">
                  <el-button
                    type="primary"
                    size="small"
                    @click="
                      downloadInvoice(
                        `${BASE_URL}${currentOrder.invoiceImageUrl}`
                      )
                    "
                  >
                    下载发票
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="
                      previewInvoice(
                        `${BASE_URL}${currentOrder.invoiceImageUrl}`
                      )
                    "
                  >
                    预览发票
                  </el-button>
                </div>
              </div>
              <span v-else class="text-gray-400">未上传</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 订单商品 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单商品</span>
            </div>
          </template>
          <el-table
            :data="currentOrder.orderItems || []"
            border
            style="width: 100%"
          >
            <el-table-column prop="id" label="商品ID" width="120" />
            <el-table-column label="商品图片" width="100">
              <template #default="scope">
                <el-image
                  :src="`${BASE_URL}${scope.row.product?.pImgUrl}`"
                  style="width: 50px; height: 50px"
                  fit="cover"
                />
              </template>
            </el-table-column>
            <el-table-column prop="product.pName" label="商品名称" />
            <el-table-column prop="product.pBrand" label="商品品牌" />
            <el-table-column prop="product.pType" label="商品类型" />
            <el-table-column prop="product.pSpecifications" label="商品规格" />
            <el-table-column prop="product.pPrice" label="商品单价" />
            <el-table-column prop="pNumber" label="购买数量" />
            <el-table-column label="订单价格">
              <template #default="scope">
                ¥{{ getItemOrderPrice(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="商品状态" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.product?.isActive ? 'success' : 'danger'"
                >
                  {{ scope.row.product?.isActive ? "激活" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单状态修改弹窗 -->
    <OrderStatusDialog
      v-model:visible="statusDialogVisible"
      :order-id="editingOrderId"
      :current-status="editingOrderStatus"
      :order-data="editingOrderData"
      @success="onStatusUpdateSuccess"
    />

    <!-- 发票上传弹窗 -->
    <el-dialog
      v-model="invoiceUploadVisible"
      title="上传发票"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="invoice-upload-container">
        <el-upload
          ref="invoiceUploadRef"
          class="upload-demo"
          drag
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-success="handleInvoiceUploadSuccess"
          :on-error="handleInvoiceUploadError"
          :before-upload="beforeInvoiceUpload"
          :on-change="handleInvoiceFileChange"
          :on-remove="handleInvoiceFileRemove"
          :file-list="invoiceFileList"
          :auto-upload="false"
          accept=".pdf,.ofd"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将发票文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只支持 PDF、OFD 格式的发票文件，单张不超过 5MB
            </div>
          </template>
        </el-upload>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeInvoiceUpload">取消</el-button>
          <el-button
            type="primary"
            @click="submitInvoiceUpload"
            :loading="invoiceUploading"
          >
            确定上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
// @ts-ignore
import {
  Search,
  Plus,
  Delete,
  UploadFilled,
  Refresh,
  Download,
} from "@element-plus/icons-vue";
import { useTable } from "@/hooks/useTable";
import tableApi from "@/api/table";
import "@imengyu/vue3-context-menu/lib/vue3-context-menu.css";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import orderApi from "@/api/order";
import {
  add,
  subtract,
  formatAmount,
  safeNumber,
  calculateTotalPrice,
} from "@/utils/precision";
// BASE_URL配置
const BASE_URL = import.meta.env.VITE_BASE_URL;

//导入组件右键菜单组件
// @ts-ignore
import {
  ContextMenu,
  ContextMenuGroup,
  ContextMenuItem,
} from "@imengyu/vue3-context-menu";
import type { MenuOptions } from "@imengyu/vue3-context-menu";
// @ts-ignore
import OrderStatusDialog from "@/components/order-status-dialog/Index.vue";

const queryForm = reactive({
  keyword: "",
  orderType: "",
});
const { tableData, pagination, total, loading } = useTable(
  tableApi.packTableList,
  queryForm
);

// 重写数据获取逻辑以支持前端筛选
const getTableDataWithFilter = async () => {
  loading.value = true;
  try {
    const params = { ...queryForm, ...pagination };
    const res = await tableApi.packTableList(params);
    // 保存所有数据
    allTableData.value = res.data.list || [];

    // 应用状态筛选
    applyStatusFilter();

    total.value = res.data.total;
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
let show = ref(false);
const optionsComponent: MenuOptions = reactive({
  zIndex: 3,
  minWidth: 230,
  x: 500,
  y: 200,
});
// 批量操作相关
const selectedRows = ref<any[]>([]);
const tableRef = ref();
const downloadLoading = ref(false);
// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};
// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage({
      message: "请先选择要删除的订单",
      type: "warning",
    });
    return;
  }

  // 添加确认对话框
  try {
    await ElMessageBox.confirm(
      `确认要删除选中的 ${selectedRows.value.length} 个订单吗？此操作不可逆！`,
      "批量删除确认",
      {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger",
      }
    );
  } catch {
    // 用户取消删除
    return;
  }

  try {
    // 验证选中的行是否有效
    if (!selectedRows.value || selectedRows.value.length === 0) {
      ElMessage.warning("没有选中任何订单");
      return;
    }

    // 检查选中的行是否都有有效的ID
    const invalidRows = selectedRows.value.filter(
      (row) => !row.id || typeof row.id !== "string"
    );
    if (invalidRows.length > 0) {
      ElMessage.error("选中的订单中包含无效数据，请刷新页面后重试");
      return;
    }

    const orderIds: string[] = selectedRows.value.map((item) => item.id);
    const data = {
      orderIds,
    };

    const res: any = await orderApi.batchDeleteSome(data);

    // 根据全局响应拦截器的包装结构：
    // 外层: { data: 服务层返回, success: true, ok: true }
    // 内层: { ok: true/false, message: string, data?: {...} }
    if (res.data && res.data.ok) {
      const actualDeletedCount =
        res.data?.data?.deletedCount || orderIds.length;
      ElMessage({
        message:
          res.data.message ||
          `批量删除成功，共删除 ${actualDeletedCount} 个订单`,
        type: "success",
      });

      // 清除选择
      clearSelection();

      // 刷新表格数据
      refreshTableInfoWithFilter();
    } else {
      // 业务逻辑失败 - 显示具体的错误信息
      const errorMsg = res.data?.message || "删除失败";

      ElMessage({
        message: `批量删除失败: ${errorMsg}`,
        type: "error",
        duration: 5000,
      });
    }
  } catch (error) {
    ElMessage({
      message: "删除失败，请重试",
      type: "error",
    });
  }
};
// 清除选择
const clearSelection = () => {
  selectedRows.value = [];
  // 清除表格选择状态
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};
// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    PENDING: "待确认",
    PENDING_SHIP: "待发货",
    SHIPPED: "已发货",
    PENDING_PAYMENT: "待付款",
    COMPLETED: "已完成",
    RETURN_REQUESTED: "申请退货",
    RETURN_APPROVED: "退货同意",
    RETURN_REJECTED: "退货拒绝",
    RETURNED: "已退货",
    CANCELLED: "已取消",
  };
  return statusMap[status] || "未知状态";
};

// 获取显示金额（退货同意/已退货状态显示剩余金额）
const getDisplayAmount = (order: any) => {
  if (!order) return "0.00";

  const originalTotal = safeNumber(order.orderPrice, 0);

  // 如果是退货同意或已退货状态，计算剩余金额
  if (order.status === "RETURN_APPROVED" || order.status === "RETURNED") {
    const returnAmount = calculateReturnAmount(order);
    const remainingTotal = subtract(originalTotal, returnAmount, 2);
    return formatAmount(Math.max(0, remainingTotal), 2);
  }

  // 其他状态显示原金额
  return formatAmount(originalTotal, 2);
};

// 计算退货商品金额
const calculateReturnAmount = (order: any) => {
  if (!order || !order.orderItems) return 0;

  try {
    // 尝试解析 remark 字段中的退货商品信息
    if (order.remark) {
      const returnItems = JSON.parse(order.remark);

      // 如果成功解析出退货商品信息，说明是部分退货
      if (Array.isArray(returnItems) && returnItems.length > 0) {
        return order.orderItems
          .filter((orderItem: any) => {
            return returnItems.some(
              (returnItem: any) => returnItem.orderItemId === orderItem.id
            );
          })
          .reduce((sum: number, orderItem: any) => {
            const returnItem = returnItems.find(
              (ri: any) => ri.orderItemId === orderItem.id
            );
            const quantity = returnItem
              ? safeNumber(returnItem.returnQuantity, 0)
              : safeNumber(orderItem.pNumber, 0);
            const price = safeNumber(orderItem.pPrice, 0);
            const itemTotal = calculateTotalPrice(quantity, price, 2);
            return add(sum, itemTotal, 2);
          }, 0);
      }
    }

    // 如果没有具体的退货商品信息，说明是整单退货
    return order.orderItems.reduce((sum: number, item: any) => {
      const quantity = safeNumber(item.pNumber, 0);
      const price = safeNumber(item.pPrice, 0);
      const itemTotal = calculateTotalPrice(quantity, price, 2);
      return add(sum, itemTotal, 2);
    }, 0);
  } catch (error) {
    console.warn("计算退货金额失败:", error);
    // 解析失败时，按整单退货计算
    return order.orderItems.reduce((sum: number, item: any) => {
      const quantity = safeNumber(item.pNumber, 0);
      const price = safeNumber(item.pPrice, 0);
      const itemTotal = calculateTotalPrice(quantity, price, 2);
      return add(sum, itemTotal, 2);
    }, 0);
  }
};

// 计算商品订单价格（单价 × 数量）
const getItemOrderPrice = (item: any) => {
  const quantity = safeNumber(item.pNumber, 0);
  const price = safeNumber(item.pPrice, 0);
  return formatAmount(calculateTotalPrice(quantity, price, 2), 2);
};

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    PENDING: "info",
    PENDING_SHIP: "info",
    SHIPPED: "success",
    PENDING_PAYMENT: "warning",
    COMPLETED: "success",
    RETURN_REQUESTED: "primary",
    RETURN_APPROVED: "danger",
    RETURN_REJECTED: "info",
    RETURNED: "danger",
    CANCELLED: "danger",
  };
  return typeMap[status] || "info";
};

const handleRowContextmenu = (row: any, column: any, event: any) => {
  event.preventDefault();
  show.value = true;
  optionsComponent.x = event.clientX;
  optionsComponent.y = event.clientY;
};

import type { TabsPaneContext } from "element-plus";
const activeName = ref("");
const handleClick = (tab: TabsPaneContext) => {
  // 根据标签页设置状态筛选
  if (tab.paneName === "") {
    // 全部订单 - 不做筛选
    currentStatus.value = "";
  } else if (tab.paneName) {
    // 根据状态筛选
    currentStatus.value = String(tab.paneName);
  }
  // 应用筛选
  applyStatusFilter();
};
const onMenuClick = (index?: number) => {};

// 详情弹窗相关变量
const detailsVisible = ref(false);
const currentOrder = ref<any>(null);

// 状态筛选相关变量
const currentStatus = ref<string>(""); // 当前选中的状态，空字符串表示全部
const allTableData = ref<any[]>([]); // 存储所有数据

const onDetailsClick = async (row: any) => {
  currentOrder.value = row;
  detailsVisible.value = true;

  // 如果是已完成订单或已退货订单，获取发票信息
  if (row.status === "COMPLETED" || row.status === "RETURNED") {
    await loadInvoiceInfo(row.id);
  }
};
// 状态修改弹窗相关变量
const statusDialogVisible = ref(false);
const editingOrderId = ref("");
const editingOrderStatus = ref("");
const editingOrderData = ref<any>(null);

const onEditStatus = (row: any) => {
  editingOrderId.value = row.id;
  editingOrderStatus.value = row.status || "";
  editingOrderData.value = row; // 传递完整的订单数据
  statusDialogVisible.value = true;
};

// 状态修改成功处理
const onStatusUpdateSuccess = () => {
  refreshTableInfoWithFilter();
};

// 判断是否显示退货信息
const shouldShowReturnInfo = (status: string) => {
  const returnStatuses = [
    "RETURN_REQUESTED",
    "RETURN_APPROVED",
    "RETURN_REJECTED",
    "RETURNED",
  ];
  return returnStatuses.includes(status);
};

// 获取完整地址（省市区 + 详细地址）
const getFullAddress = (address: any) => {
  if (!address) {
    return "暂无收货地址";
  }

  const region = address.region || "";
  const detailAddress = address.address || "";

  if (!region && !detailAddress) {
    return "暂无收货地址";
  }

  if (!region) {
    return detailAddress;
  }

  if (!detailAddress) {
    return region;
  }

  return `${region} ${detailAddress}`;
};

// 获取退货商品列表
const getReturnItems = (order: any) => {
  if (!order || !order.orderItems) return [];

  // 尝试解析remark中的JSON数据（新格式）
  if (order.remark && order.remark.startsWith("[")) {
    try {
      const returnItems = JSON.parse(order.remark);
      return order.orderItems
        .map((item: any) => {
          const returnItem = returnItems.find(
            (r: any) => r.orderItemId === item.id
          );
          if (returnItem) {
            return {
              ...item,
              returnQuantity: returnItem.returnQuantity,
            };
          }
          return null;
        })
        .filter(Boolean);
    } catch (error) {
      console.error("解析退货数据失败:", error);
    }
  }

  // 兼容旧格式：如果remark中包含商品ID（用逗号分隔），则表示部分商品退货
  if (order.remark && order.remark.includes(",")) {
    const returnItemIds = order.remark
      .split(",")
      .filter((id: string) => id.trim());
    return order.orderItems
      .filter((item: any) => returnItemIds.includes(item.id))
      .map((item: any) => ({
        ...item,
        returnQuantity: parseInt(item.pNumber), // 旧格式默认为全部数量
      }));
  }

  // 否则返回所有商品（全部退货）
  return order.orderItems.map((item: any) => ({
    ...item,
    returnQuantity: parseInt(item.pNumber),
  }));
};

// 应用状态筛选
const applyStatusFilter = () => {
  if (!currentStatus.value || currentStatus.value === "") {
    // 显示全部数据 - 不做筛选
    tableData.value = allTableData.value;
  } else {
    // 根据状态筛选数据
    tableData.value = allTableData.value.filter(
      (item) => item.status === currentStatus.value
    );
  }
};

// 重写搜索函数
const handleSearchWithFilter = () => {
  pagination.page = 1;
  getTableDataWithFilter();
};

// 重写刷新函数
const refreshTableInfoWithFilter = () => {
  currentStatus.value = ""; // 重置为全部状态
  getTableDataWithFilter();
};

const onLoopMenuClick = (index: number) => {};
const confirmEvent = async (row: any) => {
  try {
    const res: any = await orderApi.deleteOrder(row.id);

    if (res.data && res.data.ok) {
      ElMessage({
        message: res.data.message || "删除成功",
        type: "success",
      });
      refreshTableInfoWithFilter();
    } else {
      ElMessage({
        message: res.data?.message || "删除失败",
        type: "error",
      });
    }
  } catch (error) {
    ElMessage({
      message: "删除失败，请重试",
      type: "error",
    });
  }
};
const cancelEvent = () => {};

// 发票相关变量
const invoiceUploadVisible = ref(false);
const invoiceUploading = ref(false);
const invoiceFileList = ref<any[]>([]);
const invoiceUploadRef = ref();
const currentInvoiceOrderId = ref("");
const uploadUrl = `${import.meta.env.VITE_API_PREFIX}/file/fileUpload`;
const uploadHeaders = {
  // Authorization: 'Bearer ' + getToken() // 如果需要认证
};

// 发票相关方法
// 上传发票按钮点击
const uploadInvoice = (order: any) => {
  currentInvoiceOrderId.value = order.id;
  invoiceFileList.value = [];
  invoiceUploading.value = false;
  invoiceUploadVisible.value = true;

  // 清理上传组件状态
  setTimeout(() => {
    if (invoiceUploadRef.value) {
      invoiceUploadRef.value.clearFiles();
    }
  }, 100);
};

// 发票上传前验证
const beforeInvoiceUpload = (file: File) => {
  // 验证文件格式 - 只允许PDF和OFD
  const fileName = file.name.toLowerCase();
  const isPdf = fileName.endsWith(".pdf") || file.type === "application/pdf";
  const isOfd = fileName.endsWith(".ofd") || file.type === "application/ofd";
  const isValidFormat = isPdf || isOfd;
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isValidFormat) {
    ElMessage.error("只支持PDF和OFD格式的发票文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("文件大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 发票上传成功
const handleInvoiceUploadSuccess = async (response: any) => {
  // 检查文件上传是否成功
  if (
    !response.data ||
    !response.data.ok ||
    !response.data.data ||
    !response.data.data.url
  ) {
    ElMessage.error("文件上传失败");
    invoiceUploading.value = false;
    return;
  }

  try {
    // 调用后端API保存发票图片URL
    const res = await orderApi.uploadInvoiceImage(currentInvoiceOrderId.value, {
      invoiceImageUrl: response.data.data.url,
    });

    if (res.data && res.data.ok) {
      ElMessage.success("发票上传成功");
      closeInvoiceUpload(); // 使用关闭方法重置状态
      refreshTableInfoWithFilter(); // 刷新表格数据

      // 如果当前订单详情弹窗打开，强制刷新发票信息
      if (
        detailsVisible.value &&
        currentOrder.value &&
        currentOrder.value.id === currentInvoiceOrderId.value
      ) {
        // 清除现有发票信息，强制重新加载
        currentOrder.value.invoiceInfo = null;
        currentOrder.value.invoiceImageUrl = null;
        await loadInvoiceInfo(currentInvoiceOrderId.value);
      }
    } else {
      const errorMsg = res.data?.message || "保存发票信息失败";
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    ElMessage.error("保存发票信息失败");
  } finally {
    invoiceUploading.value = false;
  }
};

// 发票上传失败
const handleInvoiceUploadError = (error: any) => {
  ElMessage.error("发票上传失败");
  invoiceUploading.value = false;
};

// 提交发票上传
const submitInvoiceUpload = () => {
  if (invoiceFileList.value.length === 0) {
    ElMessage.warning("请选择要上传的发票文件");
    return;
  }

  invoiceUploading.value = true;
  invoiceUploadRef.value.submit();
};

// 发票文件变化处理
const handleInvoiceFileChange = (file: any, fileList: any[]) => {
  invoiceFileList.value = fileList;
};

// 发票文件移除处理
const handleInvoiceFileRemove = (file: any, fileList: any[]) => {
  invoiceFileList.value = fileList;
};

// 关闭发票上传弹窗
const closeInvoiceUpload = () => {
  invoiceUploadVisible.value = false;
  invoiceFileList.value = [];
  invoiceUploading.value = false;
  currentInvoiceOrderId.value = "";

  // 清理上传组件状态
  if (invoiceUploadRef.value) {
    invoiceUploadRef.value.clearFiles();
  }
};

// 加载发票信息
const loadInvoiceInfo = async (orderId: string) => {
  if (
    currentOrder.value &&
    currentOrder.value.invoiceInfo &&
    currentOrder.value.id === orderId
  ) {
    return;
  }

  try {
    const res = await orderApi.getInvoiceInfo(orderId);

    if (res.data && res.data.ok) {
      // 将发票信息合并到当前订单对象中
      currentOrder.value = {
        ...currentOrder.value,
        invoiceInfo: res.data.data.invoiceInfo,
        invoiceImageUrl: res.data.data.invoiceImageUrl,
      };
    } else {
      console.warn("获取发票信息失败，响应不符合预期:", res);
    }
  } catch (error) {}
};

// 获取发票文件名
const getInvoiceFileName = (url: string) => {
  if (!url) return "未知文件";
  const parts = url.split("/");
  return parts[parts.length - 1] || "未知文件";
};

// 获取发票文件类型
const getInvoiceFileType = (url: string) => {
  if (!url) return "未知格式";
  const extension = url.toLowerCase().split(".").pop();
  if (extension === "pdf") return "PDF格式";
  if (extension === "ofd") return "OFD格式";
  return "未知格式";
};

// 预览发票
const previewInvoice = (url: string) => {
  // 在新窗口中打开文件
  window.open(url, "_blank");
};

// 下载发票
const downloadInvoice = async (url: string) => {
  try {
    // 使用fetch获取文件
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error("下载失败");
    }

    // 获取文件blob
    const blob = await response.blob();

    // 创建下载链接
    const link = document.createElement("a");
    const objectUrl = URL.createObjectURL(blob);

    // 从URL获取文件扩展名
    const extension = url.toLowerCase().split(".").pop() || "pdf";

    link.href = objectUrl;
    link.download = `发票_${new Date().getTime()}.${extension}`;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    URL.revokeObjectURL(objectUrl);

    ElMessage.success("发票下载成功");
  } catch (error) {
    ElMessage.error("下载发票失败，请重试");
  }
};

// 批量下载订单
const batchDownload = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage({
      message: "请先选择要下载的订单",
      type: "warning",
    });
    return;
  }

  try {
    downloadLoading.value = true;

    // 获取选中订单的ID列表
    const orderIds = selectedRows.value.map((item) => item.id);

    // 调用下载API
    console.log("准备下载选中的订单，订单ID列表:", orderIds);
    const response = await orderApi.downloadOrdersExcel({
      orderIds: orderIds,
    });

    // 检查响应
    if (!response || !(response instanceof Blob)) {
      throw new Error("下载失败，响应格式不正确");
    }

    // 创建下载链接
    const blob = new Blob([response], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");

    // 生成文件名
    const timestamp = dayjs().format("YYYYMMDD_HHmmss");
    const filename = `订单导出_${timestamp}.xlsx`;

    link.href = url;
    link.download = filename;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    ElMessage.success(`成功下载 ${selectedRows.value.length} 个订单的数据`);

    // 可选：清除选择状态
    // clearSelection();
  } catch (error) {
    console.error("下载订单失败:", error);
    ElMessage({
      message: "下载订单失败，请重试",
      type: "error",
      duration: 5000,
    });
  } finally {
    downloadLoading.value = false;
  }
};
</script>
<style scoped>
.w-100 {
  width: 200px;
  margin-right: 5px;
}

.demo-tabs {
  margin-top: 30px;
}

.order-details {
  max-height: 600px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.batch-tip {
  background-color: #e1f3d8;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #67c23a;
  font-size: 14px;
}

.address-detail {
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
  padding: 4px 0;
  min-height: 20px;
}

.invoice-file-info {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  word-break: break-all;
}

.file-type {
  font-size: 12px;
  color: #007aff;
  background-color: #e6f3ff;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
}

/* 退货商品样式 */
.return-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.return-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 8px;
  border-left: 3px solid #ff6b35;
}

.item-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-name {
  font-weight: 500;
  color: #333;
}

.item-spec {
  font-size: 12px;
  color: #666;
}

.item-details {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-price {
  font-weight: 600;
  color: #ff6b35;
}

.item-quantity {
  color: #666;
  font-size: 14px;
}

/* 退货商品表格样式 */
.return-products-section {
  margin-top: 20px;
}

.product-info {
  text-align: left;
}

.product-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.product-spec {
  font-size: 12px;
  color: #999;
}

.price-text {
  font-weight: 600;
  color: #ff6b35;
}

.quantity-text {
  font-weight: 500;
  color: #333;
}

/* 在 descriptions 中的表格样式调整 */
.el-descriptions-item__content .el-table {
  margin: 0;
}

.el-descriptions-item__content .product-info {
  padding: 8px 0;
}
</style>
